﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using Tassdar.Core.Helper;

namespace Tassdar.Framework.Model.Base
{
    /// <summary>
    /// 重写EFDbContext
    /// </summary>
   public class EFDbContext: DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseMySql(ConfigHelper.GetValue<string>("ConnectionStrings:Development"));
            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //获取当前线程根目录
            string path = Thread.GetDomain().BaseDirectory;
            //读取指定程序集下所有实体。使用者可以根据自己的用户更改程序集名称
            Assembly[] assemblies = new DirectoryInfo(path).GetFiles("Tassdar.Framework.dll", SearchOption.AllDirectories)
                .Select(x => Assembly.LoadFrom(x.FullName)).ToArray();
            Type  baseType = typeof(EntityBase);
            foreach (var assembly in assemblies)
            {
                //找出所有继承了BaseEntity的类
                IEnumerable<Type> entityTypes = assembly.GetTypes().Where(x => x.IsSubclassOf(baseType));
                //把实体映射到EFCore
                foreach (var type in entityTypes)
                {
                    modelBuilder.Entity(type);
                }
            }
            base.OnModelCreating(modelBuilder);
        }
    }
}
